//
//  WLComposeViewController.swift
//  WLWeibo
//
//  Created by Devil on 16/8/17.
//  Copyright © 2016年 Wiliam. All rights reserved.
//

import UIKit

class WLComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

    }
    @objc private func cancelAction(){
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func sendAction(){
        print("发布按钮点击")
    
    }
    
    private func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        //添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        composeTextView.addSubview(composePictureView)
        //添加约束
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composeBottomView.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        composePictureView.snp_makeConstraints { (make) in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(composeTextView)
        }
        
        composeBottomView.closure = {[weak self] (type: WLComposeBottomViewType) -> () in
            
            switch type {
            case .Picture:
                print("图片")
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("笑脸")
            case .Add:
                print("+")
            }
        }
        //配图闭包回调
        composePictureView.closure = {[weak self] in
            self?.selectImages()
        }
        //注册通知 监听键盘将要改变frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "KeyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    //监听键盘frame改变
    func KeyboardWillChangeFrame(noti: NSNotification){
        //动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        //判断是否为nil   是否可以转成NSValue
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        //获取到CGRect
        let newRect = rect.CGRectValue()
        //更新约束
        composeBottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        //设置动画
        UIView.animateWithDuration(duration){() -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    
    private func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    //懒加载控件
    private lazy var titleView: UILabel = {
        //用户昵称
        let name = WLUserAccountViewModel.sharedTools.userAccount!.screen_name!
        //显示内容
        let str = "发微博\n\(name)"
        //获取范围
        let range = (str as NSString).rangeOfString(name)
        //初始化一个副文本
        let attr = NSMutableAttributedString(string: str)
        //设置副文本
        attr.addAttributes([NSForegroundColorAttributeName: AppThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(12) ], range: range )
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.attributedText = attr
        label.sizeToFit()
        return label
    }()
    //自定义textView
    private lazy var composeTextView:WLComposeTextView = {
        let view = WLComposeTextView()
        view.delegate = self
        //设置字体
        view.font = UIFont.systemFontOfSize(16)
        //设置占位文字
        view.placeholder = "传智31期"
        //允许上下移动
        view.alwaysBounceVertical = true
        return view
    }()
    //自定义底部视图
    private lazy var composeBottomView: WLComposeBottomView = WLComposeBottomView()
    //配图
    private lazy var composePictureView: WLComposePictureView = WLComposePictureView()
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
//处理composeBottomView按钮事件
extension WLComposeViewController{
    func selectImages(){
        let pickerVc = UIImagePickerController()
        //设置代理
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
        
    
    }
}

extension WLComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
        composeTextView.backgroundColor = UIColor(patternImage: image)
        //添加图片
        composePictureView.addImages(image)
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

}

//UITextViewDelegate
extension WLComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //取消键盘第一响应
        self.composeTextView.resignFirstResponder()
    }
}















